<template>
    <el-container class="supplier_container">
        <vAside ref="aside" :options="asideOptions"
                :treeOptions="treeOptions"
                :treeData="treeData"
                @event="handleAsideEvent">
            <template slot="button">
                <i class="ml5 el-icon-circle-plus-outline"
                   v-permission="'save_sys_supplier_type'"
                   @click="openTypeDialog(null, 'add')" />
                <el-tooltip class="item" effect="dark"
                            content="全部供应商" placement="top">
                    <i class="ml10 fa fa-list-ul"
                       :style="treeData.length && !treeNodeKey.sid ? 'color:#409EFf' : ''"
                       @click="getAllList()" />
                </el-tooltip>
            </template>
        </vAside>
        <el-main>
            <el-card class="box-card">
                <headerTemplate slot="header" ref="header"
                                :table-ref="tableOptions.ref"
                                :toolbar_buttons="toolbar_buttons"
                                :toolbar_filter="toolbar_filter"
                                :searchForm="searchForm"
                                @event="handleEvent">
                    <template slot="right_search">
                        <el-form-item label="合作状态" style="margin-top: 4px; margin-bottom: 4px;">
                            <el-select v-model="searchForm.state" placeholder="请选择"
                                       @change="getList(true)" class="w100"
                                       style="margin-right: 5px;" clearable>
                                <el-option v-for="(item, index) in stateList"
                                           :key="index" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </template>
                </headerTemplate>
                <vxeTableTemplate :data="dataList" :options.sync="tableOptions"
                                  @event="handleTableEvent" />
            </el-card>

            <component-dialog dialog-drag :options="componentDialogOption" @event="handleDialogEvent" />
        </el-main>
    </el-container>
</template>

<script>
import baseRelatedPartyApi from "@common/api/base/baseRelatedPartyApi";
import SupplierForm from "../dialog/supplier/SupplierForm";
import TypeForm from "../dialog/components/TypeForm";
import provide from "@common/mixins/provide";

export default {
    extends: provide,
    name: "sysSupplier",
    provide() {
        return {
            setChildrenRef: (name, ref) => {
                this[name] = ref;
            },
            getChildrenRef: (name) => {
                return this[name];
            },
            getRef: () => {
                return this;
            },
        };
    },
    data() {
        let $this = this;
        return {
            isShrink: true,
            toolbar_buttons: [
                {
                    id: "refresh",
                    icon: "fa fa-refresh",
                    show: true,
                    method: () => {
                        $this.getList();
                    },
                },
                {
                    id: "add",
                    type: "primary",
                    icon: "fa fa-plus",
                    show: true,
                    permission: "save_sys_supplier",
                    method: () => {
                        $this.openDialog(null, "add");
                    },
                },
                {
                    id: "edit",
                    type: "success",
                    icon: "fa fa-pencil",
                    show: true,
                    permission: "save_sys_supplier",
                    method: () => {
                        $this.openDialog(null, "edit");
                    },
                },
                {
                    id: "del",
                    type: "danger",
                    icon: "fa fa-trash-o",
                    show: true,
                    permission: "del_sys_supplier",
                    method: () => {
                        $this.confirmDel();
                    },
                },
            ], //左侧按钮
            toolbar_filter: [], //精确筛选
            dataList: [],
            tableOptions: {
                ref: "clientsTable",
                container: ".supplier_container",
                multiSelect: true,
                columns: [
                    {
                        label: "编码",
                        prop: "code",
                        align: "center",
                    },
                    {
                        label: "名称",
                        prop: "name",
                        align: "center",
                    },
                    {
                        label: "简称",
                        prop: "short_name",
                        align: "center",
                    },
                    {
                        label: "助记码",
                        prop: "search_code",
                        align: "center",
                    },
                    {
                        label: "电话",
                        prop: "phone",
                        align: "center",
                    },
                    {
                        label: "传真",
                        prop: "faxes",
                        align: "center",
                    },
                    {
                        label: "联系人",
                        prop: "contract_person_name",
                        align: "center",
                    },
                    {
                        label: "联系人电话",
                        prop: "contract_person_phone",
                        align: "center",
                        width: 150,
                    },
                    {
                        label: "邮箱",
                        prop: "contract_person_email",
                        align: "center",
                    },
                    {
                        label: "合作状态",
                        prop: "state",
                        align: "center",
                        render(h, { row, column }) {
                            return h("el-switch", {
                                props: {
                                    value: row[column.prop] === 1,
                                },
                                on: {
                                    change(value) {
                                        $this.$set(row, column.prop, value === true ? 1 : 0);
                                        $this.saveRow(row);
                                    },
                                },
                            });
                        },
                    },
                    {
                        label: "期初金额",
                        prop: "init_amount",
                        align: "center",
                        minWidth: 90,
                    },
                    {
                        label: "期初日期",
                        prop: "init_date",
                        align: "center",
                        minWidth: 90,
                    },
                    {
                        label: "当前金额",
                        prop: "amount",
                        align: "center",
                        minWidth: 90,
                    },
                ],
                operates: {
                    // width: 150,
                    fixed: "right",
                    list: [
                        {
                            id: "edit",
                            icon: "fa fa-pencil",
                            type: "success",
                            show: true,
                            tooltip: {
                                content: "编辑",
                            },
                            permission: "save_sys_supplier",
                            method: (key, row, index) => {
                                $this.openDialog(row, "edit");
                            },
                        },
                        {
                            id: "info",
                            icon: "fa fa-trash-o",
                            type: "danger",
                            tooltip: {
                                content: "删除",
                            },
                            permission: "del_sys_supplier",
                            show: true,
                            method: (key, row, index) => {
                                $this.confirmDel(row);
                            },
                        },
                    ],
                },
                pagination: {
                    pageIndex: 1,
                },
            },
            searchForm: {
                state: '',
            },
            stateList: [
                { label: '全部', value: '' },
                { label: '合作', value: 1 },
                { label: '不合作', value: 0 },
            ],
            selectionList: [],
            initTreeList: [],
            treeOptions: {
                ref: "$checkTree",
                highlightCurrent: true,
                defaultExpandAll: true,
                props: {
                    label: "name",
                    children: "children",
                },
                buttons: [
                    {
                        icon: "el-icon-circle-plus-outline",
                        permission: "save_sys_supplier_type",
                        filter(data) {
                            return data.id !== -1;
                        },
                        method: (data, $event) => {
                            $this.openTypeDialog(data, "add");
                        },
                    },
                    {
                        icon: "fa fa-pencil",
                        permission: "save_sys_supplier_type",
                        filter(data) {
                            return data.id !== -1;
                        },
                        method: (data, $event) => {
                            $this.openTypeDialog(data, "edit");
                        },
                    },
                    {
                        icon: "fa fa-trash-o",
                        permission: "del_sys_supplier_type",
                        filter(data) {
                            return data.id !== -1;
                        },
                        method: (data, $event) => {
                            $this.handleClientTypeConfirm(data);
                        },
                    },
                ], //右侧按钮
            },
            treeData: [],
            asideOptions: {
                width: "300px",
                title: "供应商分类",
            },
            //弹窗option
            dialogOption: {
                visible: false,
            },
            //员工弹窗option
            SupplierDrawerOption: {
                visible: false,
            },
            rules: {
                name: [
                    { required: true, message: "请输入名称", trigger: "blur" },
                    //目前只兼容中文、大小写英文、数字
                    {
                        // pattern: /^[A-Za-z0-9\u4e00-\u9fa5]{1,50}$/,
                        // message:
                        //   "最大 50 位大小写英文、数字或者其它地区语言字符，不能包含特殊字符",
                        max: 50,
                        message: "最大 50 位字符，内容过长，请删减",
                        trigger: "blur",
                    },
                ],
            },
            //编辑新增的form数据
            groupForm: {},
            treeNodeKey: {}, //当前选中树节点
        };
    },
    mounted() {
        this.initTreeData();
    },
    methods: {
        // 获取分类树的数据
        initTreeData() {
            let $this = this;
            let queryData = {};
            sysSupplierApi.findSysSupplierTypeTree(queryData, (result) => {
                $this.initTreeList = result.data || [];
                $this.treeData = [ { "id": -1, "sid": "-1", "name": "未分类" } ].concat(result.data || []);
                if ($this.treeNodeKey.id) {
                    $this.$nextTick(() => {
                        $this.$checkTree.setCurrentKey($this.treeNodeKey.id);
                    });
                } else if ($this.treeData && $this.treeData.length > 0) {
                    $this.$nextTick(() => {
                        $this.$checkTree.setCurrentKey($this.treeData[0].id);
                        $this.treeNodeKey = $this.treeData[0];
                        $this.getList();
                    });
                }
            });
        },
        openTypeDialog(row, type) {
            const _this = this;
            let title = type === 'add' ? '创建分类' : '编辑分类';
            if (type === 'add') {
                row = {
                    parent_sid: row ? row.sid : null,
                };
            }
            _this.openComponentDialog({
                width: '400px',
                title,
                component: TypeForm,
                propsData: {
                    api: _this.$api.API_SaveSysSupplierType,
                    row,
                },
                callback() {
                    _this.initTreeData();
                },
            });
        },
        // 分类删除确认
        handleClientTypeConfirm(data) {
            let $this = this;
            if (data.children && data.children.length) {
                return $this.$message.warning("存在下级分类，请先删除下级分类");
            }
            $this.$confirm("是否继续删除？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                sysSupplierApi.deleteSysSupplierType({ id: data.id }, () => {
                    if (data.id === $this.treeNodeKey.id) {
                        $this.treeNodeKey = {};
                    }
                    $this.initTreeData();
                    $this.$message.success("删除成功");
                });
            }).catch(() => {
            });
        },
        // 接收当前点击分类
        handleAsideEvent(event) {
            let $this = this;
            if (event.type === "nodeClick") {
                $this.treeNodeKey = event.data;
                $this.getList();
            }
        },
        // 全部按钮点击事件
        getAllList() {
            let $this = this;
            $this.treeNodeKey = {};
            $this.$checkTree && $this.$checkTree.setCurrentKey(null);
            $this.tableOptions.pagination.pageIndex = 1;
            $this.getList();
        },
        // 接收搜索条件
        handleEvent(event) {
            let $this = this;
            $this.searchForm = $.extend({}, $this.searchForm, event.searchForm);
            if (event.type === "search") {
                $this.getList(true);
            } else if (event.type === "refresh") {
                $this.getList(true);
            }
        },
        // 行点击事件，并修改值
        saveRow(row) {
            // console.log(row);
            let $this = this;
            sysSupplierApi.saveSysSupplier(row, (result) => {
                $this.$message.success("保存成功！");
            });
        },
        rowCopy(row) {
            let $this = this;
            let arr = [];
            $this.tableOptions.columns.forEach((item) => {
                if (item.prop !== "state") arr.push(row[item.prop]);
            });
            let Str = arr.join(" ");
            if ($this.$XEUtils.stringCopy(Str)) {
                $this.$message.success("复制成功！");
            } else {
                $this.$message.success("复制失败");
            }
        },
        // 获取客户列表
        getList(search) {
            let $this = this;
            $this.dataList = [];
            if (search) {
                $this.tableOptions = $this.resetTablePagination($this.tableOptions);
            }
            let queryData = $this.getQueryParams($this.tableOptions, $this.searchForm);
            if ($this.treeNodeKey.sid) {
                queryData.supplier_type_sid = $this.treeNodeKey.sid;
            } else {
                delete queryData.supplier_type_sid;
            }
            sysSupplierApi.findSysSuppliers(queryData, (result) => {
                $this.dataList = result.data || [];
                $this.tableOptions = $this.setTableTotal($this.tableOptions, result);
            });
        },
        handleTableEvent(event) {
            if (event.type === 'page') {
                this.getList();
                return;
            }
            if (event.type === 'selectionChange') {
                this.selectionList = event.value;
            }
        },
        openDialog(row, type) {
            const _this = this;
            let title = type === "add" ? "创建" : "编辑";
            if (!row) {
                if (type === 'add') {
                    row = {};
                    if(_this.treeNodeKey && _this.treeNodeKey.sid) {
                        row = {supplier_type_sid: _this.treeNodeKey.sid};
                    }
                }
                if (type === 'edit') {
                    if (!_this.checkSelection(_this.selectionList)) {
                        return;
                    }
                    row = $.extend({}, _this.selectionList[0]);
                }
            }
            _this.openComponentDialog({
                width: '60%',
                title,
                component: SupplierForm,
                propsData: {
                    row,
                    treeList: _this.initTreeList,
                },
                noCloseBtn: true,
                btns: [],
            });
        },
        handleDialogEvent(event) {
            if (event.type === 'refresh') {
                this.getList();
            }
        },
        // 确认删除用户
        confirmDel(row) {
            let $this = this;
            let ids = [];
            if (!row) {
                if (!$this.checkSelection($this.selectionList)) {
                    return;
                }
                ids = $this.selectionList.map(item => item.id);
            } else {
                ids.push(row.id);
            }
            $this.$confirm("是否继续删除？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                sysSupplierApi.batchDeleteSysSupplier({ id_list: ids }, () => {
                    $this.getList();
                    $this.$message.success("删除成功");
                });
            }).catch(() => {
            });
        },
    },
};
</script>
